<template>
	<view class="container">
		<view class="header">
			<view class="title">学习记录</view>
			<view class="filter-section">
				<view 
					class="filter-item" 
					v-for="(item, index) in filterOptions" 
					:key="index"
					:class="{'active': currentFilter === item.value}"
					@click="changeFilter(item.value)"
				>
					{{item.label}}
				</view>
			</view>
		</view>
		
		<!-- 学习统计 -->
		<view class="statistics-section">
			<view class="stat-item">
				<text class="stat-value">{{statistics.totalCount || 0}}</text>
				<text class="stat-label">总学习内容</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{statistics.completedCount || 0}}</text>
				<text class="stat-label">已完成</text>
			</view>
		</view>
		
		<view class="empty-box" v-if="recordList.length === 0">
			<image class="empty-icon" src="/static/images/empty-box.png" mode="aspectFit"></image>
			<text class="empty-text">暂无学习记录</text>
		</view>
		
		<scroll-view scroll-y class="record-list" v-else>
			<!-- 学习记录列表 -->
			<view class="record-item" v-for="(item, index) in recordList" :key="index" @click="openDetail(item)">
				<view class="item-content">
					<view class="item-title">{{item.title}}</view>
					<view class="item-summary" v-if="item.summary">{{item.summary}}</view>
					<view class="item-meta">
											<text class="item-type" v-if="item.content_type === 'rule'">规则</text>
					<text class="item-status completed" v-if="item.completed">已完成</text>
						<text class="item-status learning" v-else>学习中</text>
						<text class="item-date">{{formatDate(item.last_learn_date)}}</text>
					</view>

				</view>
				
				<view class="item-actions">
					<view class="action-btn" :class="{'review': item.completed, 'continue': !item.completed}">
						<text class="action-text">{{item.completed ? '重新学习' : '继续学习'}}</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 加载更多 -->
		<view class="load-more" v-if="recordList.length > 0 && hasMore">
			<text class="load-text" @click="loadMore">加载更多</text>
		</view>
		
		<!-- 底部提示 -->
		<view class="bottom-tip" v-if="recordList.length > 0 && !hasMore">
			<text class="tip-text">没有更多内容了</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				filterOptions: [
					{label: '全部', value: 'all'},
					{label: '规则', value: 'rule'},
					{label: '已完成', value: 'completed'},
					{label: '学习中', value: 'learning'}
				],
				currentFilter: 'all',
				recordList: [],
				statistics: {
					totalCount: 0,
					completedCount: 0,
					totalDuration: 0
				},
				page: 1,
				pageSize: 10,
				hasMore: true,
				isLoading: false
			}
		},
		onLoad() {
			// 获取学习统计
			this.getLearningStatistics();
			
			// 获取学习记录列表
			this.getLearningRecords();
		},
		onPullDownRefresh() {
			// 下拉刷新
			this.refreshLearningRecords();
		},
		methods: {
			// 下拉刷新学习记录
			refreshLearningRecords() {
				console.log('开始下拉刷新学习记录');
				
				// 重置分页
				this.page = 1;
				this.recordList = [];
				this.hasMore = true;
				
				// 同时刷新统计和记录
				Promise.all([
					this.getLearningStatisticsPromise(),
					this.getLearningRecordsPromise(false)
				]).then(() => {
					uni.showToast({
						title: '刷新成功',
						icon: 'success',
						duration: 1500
					});
				}).catch((error) => {
					console.error('刷新学习记录失败', error);
					uni.showToast({
						title: '刷新失败',
						icon: 'none',
						duration: 1500
					});
				}).finally(() => {
					// 停止下拉刷新动画
					uni.stopPullDownRefresh();
				});
			},
			
			// 获取学习统计（Promise版本）
			async getLearningStatisticsPromise() {
				try {
					const token = uni.getStorageSync('user_token');
					
					const learningService = uniCloud.importObject('learning-service');
					const res = await learningService.getLearningStatistics({
							token: token
					});
					
					if (res && res.code === 0) {
						console.log('获取学习统计成功:', res.data);
								this.statistics = {
							totalCount: parseInt(res.data.totalCount) || 0,
							completedCount: parseInt(res.data.completedCount) || 0,
							totalDuration: parseInt(res.data.totalDuration) || 0
								};
						return res.data;
							} else {
						console.error('获取学习统计失败:', res ? res.message : '未知错误');
								this.getMockStatistics();
						return null;
							}
				} catch (err) {
							console.error('获取学习统计失败', err);
							this.getMockStatistics();
					throw err;
						}
			},
			
			// 获取学习记录列表（Promise版本）
			async getLearningRecordsPromise(loadMore = false) {
				try {
					const token = uni.getStorageSync('user_token');
					console.log('获取学习记录，token:', token ? '有效' : '无效');
					
					const myService = uniCloud.importObject('my-service');
					const res = await myService.getUserLearningList({
							page: this.page,
							pageSize: this.pageSize,
							type: this.currentFilter === 'rule' ? this.currentFilter : '',
							completed: this.currentFilter === 'completed' ? true : (this.currentFilter === 'learning' ? false : undefined),
							token: token
					});
					
					console.log('获取学习记录响应:', res);
							
					if (res && res.code === 0) {
						const data = res.data;
								
								const processedRecords = (data.list || []).map(item => {
									const isCompleted = item.completed === true || item.is_completed === true;
									return {
										...item,
										title: item.title || '未知内容',
										completed: isCompleted,
										is_completed: isCompleted
									};
								});
								
								if (loadMore) {
									this.recordList = [...this.recordList, ...processedRecords];
								} else {
									this.recordList = processedRecords;
								}
								
								this.hasMore = data.total > this.page * this.pageSize;
						return data;
							} else {
						console.error('获取学习记录失败:', res ? res.message : '未知错误');
								this.getMockLearningRecords(loadMore);
						return null;
							}
				} catch (err) {
							console.error('获取学习记录失败', err);
							this.getMockLearningRecords(loadMore);
					throw err;
						}
			},
			
			// 获取学习统计
			async getLearningStatistics() {
				try {
					const token = uni.getStorageSync('user_token');
				
					// 调用云对象获取学习统计
					const learningService = uniCloud.importObject('learning-service');
					const res = await learningService.getLearningStatistics({
						token: token
					});
					
					if (res && res.code === 0) {
						console.log('获取学习统计成功:', res.data);
							// 确保所有值都是有效数字
							this.statistics = {
							totalCount: parseInt(res.data.totalCount) || 0,
							completedCount: parseInt(res.data.completedCount) || 0,
							totalDuration: parseInt(res.data.totalDuration) || 0
							};
						} else {
						console.error('获取学习统计失败:', res ? res.message : '未知错误');
						// 如果云对象不可用，使用模拟数据
						this.getMockStatistics();
					}
				} catch (err) {
					console.error('获取学习统计失败', err);
					// 如果云对象不可用，使用模拟数据
					this.getMockStatistics();
				}
			},
			
			// 获取模拟学习统计
			getMockStatistics() {
				this.statistics = {
					totalCount: 12,
					completedCount: 8,
					totalDuration: 320
				};
			},
			
			// 获取学习记录列表
			async getLearningRecords(loadMore = false) {
				if (this.isLoading) return;
				
				this.isLoading = true;
				
				if (!loadMore) {
					uni.showLoading({
						title: '加载中...'
					});
				}
				
				const token = uni.getStorageSync('user_token');
				console.log('获取学习记录，token:', token ? '有效' : '无效');
				
				// 调用云对象获取学习记录列表
				try {
					const myService = uniCloud.importObject('my-service');
					const res = await myService.getUserLearningList({
						page: this.page,
						pageSize: this.pageSize,
						type: this.currentFilter === 'rule' ? this.currentFilter : '',
						completed: this.currentFilter === 'completed' ? true : (this.currentFilter === 'learning' ? false : undefined),
						token: token
					});
					
					console.log('获取学习记录响应:', res);
						
					if (res && res.code === 0) {
						const data = res.data;
							
							// 处理记录，确保completed字段存在且正确
							const processedRecords = (data.list || []).map(item => {
								// 检查完成状态
								const isCompleted = item.completed === true || item.is_completed === true;
								
								// 规范化记录数据
								return {
									...item,
									// 确保标题字段存在
									title: item.title || '未知内容',
									// 统一使用completed字段表示完成状态
									completed: isCompleted,
									is_completed: isCompleted
								};
							});
							
							if (loadMore) {
								this.recordList = [...this.recordList, ...processedRecords];
							} else {
								this.recordList = processedRecords;
							}
							
							this.hasMore = data.total > this.page * this.pageSize;
							
							// 在获取记录列表后，刷新学习统计
							if (!loadMore) {
								this.getLearningStatistics();
							}
						} else {
						console.error('获取学习记录失败:', res ? res.message : '未知错误');
						// 如果云对象不可用，使用模拟数据
							this.getMockLearningRecords(loadMore);
						}
						
						this.isLoading = false;
						uni.hideLoading();
				} catch (err) {
						console.error('获取学习记录失败', err);
					// 如果云对象不可用，使用模拟数据
						this.getMockLearningRecords(loadMore);
						
						this.isLoading = false;
						uni.hideLoading();
					}
			},
			
			// 获取模拟学习记录列表
			getMockLearningRecords(loadMore = false) {
				// 模拟数据
				const mockData = [
					{
						_id: '1',
						content_id: '101',
						content_type: 'rule',
						title: '足球比赛规则 - 规则一：球场',
						is_completed: true,
						last_learn_date: new Date('2023-06-15').getTime(),
						duration: 30
					},
					{
						_id: '2',
						content_id: '102',
						content_type: 'rule',
						title: '足球比赛规则 - 规则二：球',
						is_completed: true,
						last_learn_date: new Date('2023-06-16').getTime(),
						duration: 25
					},

				];
				
				// 根据筛选条件过滤
				let filteredData = mockData;
				if (this.currentFilter === 'rule') {
					filteredData = mockData.filter(item => item.content_type === 'rule');

				} else if (this.currentFilter === 'completed') {
					filteredData = mockData.filter(item => item.is_completed);
				} else if (this.currentFilter === 'learning') {
					filteredData = mockData.filter(item => !item.is_completed);
				}
				
				// 处理数据，确保completed字段存在且正确
				filteredData = filteredData.map(item => ({
					...item,
					completed: item.completed === true || item.is_completed === true
				}));
				
				// 模拟分页
				const startIndex = (this.page - 1) * this.pageSize;
				const endIndex = startIndex + this.pageSize;
				const pageData = filteredData.slice(startIndex, endIndex);
				
				if (loadMore) {
					this.recordList = [...this.recordList, ...pageData];
				} else {
					this.recordList = pageData;
				}
				
				this.hasMore = endIndex < filteredData.length;
			},
			
			// 切换筛选条件
			changeFilter(filter) {
				if (this.currentFilter === filter) return;
				
				this.currentFilter = filter;
				this.page = 1;
				this.recordList = [];
				this.hasMore = true;
				this.getLearningRecords();
			},
			
			// 加载更多
			loadMore() {
				if (!this.hasMore || this.isLoading) return;
				
				this.page++;
				this.getLearningRecords(true);
			},
			
			// 打开详情页
			openDetail(item) {
				let url = '';
				
				if (item.content_type === 'rule') {
					url = `/packageStudy/study/rule-detail?id=${item.content_id}`;
				}
				
				if (url) {
					uni.navigateTo({
						url: url
					});
				}
			},
			
			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return '';
				
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				
				return `${year}-${month}-${day}`;
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.getLearningStatistics();
			
			this.page = 1;
			this.recordList = [];
			this.hasMore = true;
			this.getLearningRecords();
			
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		// 触底加载更多
		onReachBottom() {
			this.loadMore();
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #F5F5F5;
		display: flex;
		flex-direction: column;
		width: 100%;
	}
	
	/* 头部样式 */
	.header {
		background-color: #FFFFFF;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		width: 100%;
		box-sizing: border-box;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 30rpx;
		word-wrap: break-word;
		word-break: break-all;
	}
	
	.filter-section {
		display: flex;
		border-bottom: 1rpx solid #EEEEEE;
		flex-wrap: wrap;
		width: 100%;
	}
	
	.filter-item {
		padding: 20rpx 30rpx;
		font-size: 28rpx;
		color: #666666;
		position: relative;
	}
	
	.filter-item.active {
		color: #1BAE76;
		font-weight: bold;
	}
	
	.filter-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 30rpx;
		right: 30rpx;
		height: 4rpx;
		background-color: #1BAE76;
		border-radius: 2rpx;
	}
	
	/* 统计区域样式 */
	.statistics-section {
		display: flex;
		justify-content: space-around;
		padding: 30rpx;
		background-color: #FFFFFF;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		width: 100%;
		box-sizing: border-box;
		flex-wrap: wrap;
	}
	
	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 10rpx 0;
		min-width: 30%;
	}
	
	.stat-value {
		font-size: 40rpx;
		font-weight: bold;
		color: #1BAE76;
		margin-bottom: 10rpx;
	}
	
	.stat-label {
		font-size: 24rpx;
		color: #666666;
	}
	
	/* 空状态样式 */
	.empty-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 100rpx 0;
	}
	
	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999999;
	}
	
	/* 记录列表样式 */
	.record-list {
		flex: 1;
		padding: 20rpx 30rpx;
		width: 100%;
		box-sizing: border-box;
	}
	
	.record-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		background-color: #FFFFFF;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		width: 100%;
		box-sizing: border-box;
		flex-wrap: wrap;
	}
	
	.item-content {
		flex: 1;
		margin-right: 20rpx;
		min-width: 60%;
		word-wrap: break-word;
		word-break: break-all;
	}
	
	.item-title {
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 10rpx;
		line-height: 1.4;
		word-wrap: break-word;
		word-break: break-all;
	}
	
	.item-summary {
		font-size: 24rpx;
		color: #666666;
		margin-bottom: 10rpx;
	}
	
	.item-meta {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}
	
	.item-type {
		font-size: 24rpx;
		color: #1BAE76;
		background-color: rgba(0, 127, 79, 0.1);
		padding: 4rpx 16rpx;
		border-radius: 20rpx;
		margin-right: 20rpx;
	}
	
	.item-status {
		font-size: 24rpx;
		color: #666666;
		background-color: rgba(102, 102, 102, 0.1);
		padding: 4rpx 16rpx;
		border-radius: 20rpx;
		margin-right: 20rpx;
	}
	
	.item-status.completed {
		color: #1BAE76;
		background-color: rgba(0, 127, 79, 0.1);
	}
	
	.item-status.learning {
		color: #666666;
		background-color: rgba(102, 102, 102, 0.1);
	}
	
	.item-date {
		font-size: 24rpx;
		color: #999999;
	}
	
	.progress-bar {
		height: 6rpx;
		background-color: #EEEEEE;
		border-radius: 3rpx;
		overflow: hidden;
		margin-top: 10rpx;
	}
	
	.progress-inner {
		height: 100%;
		background-color: #1BAE76;
	}
	
	.item-actions {
		display: flex;
	}
	
	.action-btn {
		padding: 10rpx 20rpx;
		border-radius: 30rpx;
		background-color: #1BAE76;
	}
	
	.action-btn.review {
		background-color: #F5F5F5;
	}
	
	.action-text {
		font-size: 24rpx;
		color: #FFFFFF;
	}
	
	.action-btn.review .action-text {
		color: #666666;
	}
	
	/* 加载更多样式 */
	.load-more {
		text-align: center;
		padding: 30rpx 0;
	}
	
	.load-text {
		font-size: 28rpx;
		color: #1BAE76;
	}
	
	/* 底部提示样式 */
	.bottom-tip {
		text-align: center;
		padding: 30rpx 0;
	}
	
	.tip-text {
		font-size: 24rpx;
		color: #999999;
	}
</style> 